package com.wzw.springboot.principle.use.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源配置类
 *
 * @author Wangzhiwen
 */
@Configuration
@ConditionalOnExpression("!'${spring.datasource.dynamic}'.isEmpty()")
@EnableConfigurationProperties(value = DynamicDatasourceProperties.class)
public class DynamicDatasourceConfiguration {

    private final DynamicDatasourceProperties dynamicDatasourceProperties;

    public DynamicDatasourceConfiguration(DynamicDatasourceProperties dynamicDatasourceProperties) {
        this.dynamicDatasourceProperties = dynamicDatasourceProperties;
    }

    @Bean
    @Primary
    public RoutingDataSource routingDataSource() {
        RoutingDataSource datasourceSwitch = new RoutingDataSource();
        // 设置目标数据源
        Map<String, DataSourceProperties> datasourceProperties = dynamicDatasourceProperties.getDynamic();
        Map<Object, Object> targetDatasource = new HashMap<>(datasourceProperties.size());
        datasourceProperties.forEach((flag, properties) -> {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(properties.getUrl());
            config.setDriverClassName(properties.getDriverClassName());
            config.setUsername(properties.getUsername());
            config.setPassword(properties.getPassword());
            config.setAutoCommit(true);
            config.setPoolName(flag + "-datasource-pool");
            config.setMaximumPoolSize(10);
            HikariDataSource dataSource = new HikariDataSource(config);
            // 设置默认数据源
            if (flag.equals(DatasourceEnum.DEFAULT.name().toLowerCase())) {
                datasourceSwitch.setDefaultTargetDataSource(dataSource);
            }
            targetDatasource.put(flag, dataSource);
        });
        datasourceSwitch.setTargetDataSources(targetDatasource);
        return datasourceSwitch;
    }

}
